package com.arlen.centre.service.impl;

import com.arlen.centre.service.WxAccessToken;
import com.arlen.common.constant.GetHttpConstant;
import com.arlen.common.result.Result;
import com.arlen.until.http.Interaction;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service //获取Access_token服务
public class WxAccessTokenImpl implements WxAccessToken {
    private final String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    @Autowired
    Interaction interaction;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public Result getAccessToken(String appId, String appSecret) throws IOException {
        if (StringUtils.isBlank(appId) && StringUtils.isBlank(appSecret)) {
            return new Result(Result.ERROR);
        }
        String token;

        token = (String) redisTemplate.opsForValue().get(appId);

        if (StringUtils.isBlank(token)) {
            String url = this.url.replace("APPID", appId).replace("APPSECRET", appSecret);
            token = interaction.sendGet(url, GetHttpConstant.ANALYSIS.getState());

            redisTemplate.opsForValue().set(appId, token, 7100, TimeUnit.SECONDS);
        }
        if (StringUtils.isBlank(token)){
            return new Result(Result.ERROR);
        }

        return new Result(Result.SUCCESS, "", token);
    }


}
